package com.yu.gulimall.product.exception;

import com.yu.common.exception.BizExceptionCode;
import com.yu.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@RestControllerAdvice(basePackages = "com.yu.gulimall.product.controller")
public class GuliMallException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R HandlerException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            errorMap.put(field, defaultMessage);
        });
        return R.error(BizExceptionCode.VALID_EXCEPTION.getCode(), BizExceptionCode.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R HandlerALlException(Throwable throwable) {
        return R.error(BizExceptionCode.UNKNOWN_EXCEPTION.getCode(), BizExceptionCode.UNKNOWN_EXCEPTION.getMsg());
    }

}
